package com.mo.axion.handler.deduplication.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.mo.axion.common.domain.AnchorInfo;
import com.mo.axion.common.domain.TaskInfo;
import com.mo.axion.handler.deduplication.DeduplicationHolder;
import com.mo.axion.handler.deduplication.DeduplicationParam;
import com.mo.axion.handler.deduplication.limit.LimitService;
import com.mo.axion.support.utils.LogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.Set;

/**
 * @author Mo
 * @createTime 2024/2/20 10:06
 * @description 去重服务抽象类
 */
@Slf4j
public abstract class AbstractDeduplicationService implements DeduplicationService{
    protected Integer deduplicationType;
    protected LimitService limitService;

    @Autowired
    private DeduplicationHolder deduplicationHolder;

    @Autowired
    private LogUtils logUtils;

    /**
     * 初始化 加入deduplicationHolder的serviceHolder的hashMap中
     */
    @PostConstruct
    private void init() {
        deduplicationHolder.putService(deduplicationType, this);
    }

    @Override
    public void deduplication(DeduplicationParam deduplicationParam) {
        TaskInfo taskInfo = deduplicationParam.getTaskInfo();
        Set<String> filterReceiver = limitService.limitFilter(this, taskInfo, deduplicationParam);
        //  剔除符合去重条件的用户
        if (CollUtil.isNotEmpty(filterReceiver)) {
            taskInfo.getReceiver().removeAll(filterReceiver);
        //  打印日志埋点
            logUtils.print(
                    AnchorInfo.builder()
                            .idList(filterReceiver)
                            .businessId(taskInfo.getBusinessId())
                            .messageId(taskInfo.getMessageId())
                            .bizId(taskInfo.getBizId())
                            .state(deduplicationParam.getAnchorState().getCode())
                            .build()
            );
        }
    }

    /**
     * 构建去重的业务key 由不同去重子类实现这个方法
     * @param taskInfo
     * @param receiver
     * @return
     */
    public abstract String deduplicationSingleKey(TaskInfo taskInfo, String receiver);
}
